from rest_framework import serializers
from apps.goods.models import SKU, SKUSpecification
from django.db import transaction
from celery_tasks.detail.tasks import generate_task


# class SpecRelatedSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = SKUSpecification
#         fields = ['spec_id', 'option_id']
class SpecRelatedSerializer(serializers.Serializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()


class SkuModelSerializer(serializers.ModelSerializer):
    # 标准商品
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()
    # 第三级分类
    category = serializers.StringRelatedField(read_only=True)
    category_id = serializers.IntegerField()
    # 规格信息
    specs = SpecRelatedSerializer(many=True)

    class Meta:
        model = SKU
        fields = '__all__'

    def create(self, validated_data):
        # 取出值specs
        specs = validated_data.pop('specs')
        # 1.禁止自动提交
        with transaction.atomic():
            # 2.开启事务
            sid = transaction.savepoint()
            try:
                # 1.创建sku对象
                sku = super().create(validated_data)

                # 2.创建sku的规格对象==》遍历
                for item in specs:
                    # sku规格对象需要指定sku_id,spec_id,option_id
                    item['sku_id'] = sku.id
                    SKUSpecification.objects.create(**item)
            except:
                # 3.回滚项目
                transaction.savepoint_rollback(sid)
                raise serializers.ValidationError('创建sku失败')
            else:
                # 4.提交事务
                transaction.savepoint_commit(sid)

                # 生成静态文件
                generate_task.delay(sku.id)

                return sku


class SkuSimpleSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField()
